﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;
using SN.Data;
using Agro.Library;
namespace Agro.Services
{
    public class ActionService : BaseService, IActionService
    {
        public System.Data.DataTable GetActionList(SN.Core.QueryBase query, SN.Data.WhereClip wclip)
        {
            Field[] fields = { 
                               T_Action._.All,
                               T_Menu._.Menu_NAME
                             };


            var section = DB.From<T_Action>()
                .InnerJoin<T_Menu>(T_Menu._.Menu_ID == T_Action._.MenuID)
                .Where(wclip);
            var dt = section.ToTablePage(query, fields);
            return dt;
        }

        public bool SaveAction(T_Action Action, out string msg)
        {
            msg = string.Empty;
            using (DbTrans trans = DB.BeginTrans())
            {
                try
                {
                    if (Action.ActionID > 0)
                    {
                        Action.Attach();
                    }
                    else
                    {
                        //新增
                        Action.Detach();
                    }
                    trans.Save(Action);
                    CacheKeys.ClearCacheKeys();//清除菜单缓存
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    return false;
                }
                //提交数据
                trans.Commit();
            }
            return true;
        }


        public bool DeleteAction(string ids, out string msg)
        {
            msg = string.Empty;
            if (DB.Exists<T_UserAction>(T_UserAction._.ActionID.In(ids.Split(','))))
            {
                msg = "该操作权限已在用户操作权限表中使用!";
                return false;
            }
            if (DB.Exists<T_RoleAction>(T_RoleAction._.ActionID.In(ids.Split(','))))
            {
                msg = "该操作权限已在角色操作权限表中使用!";
                return false;
            }
            //可以删除
            DB.Delete<T_Action>(T_Action._.ActionID.In(ids.Split(',')));
            return true;
        }
    }
}
